package hw1;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/sakila";
    private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    
    private static final int NUMBER_OF_QUESTIONS = 10;
    private static final String SOLUTION_DIR = "res/sol/";
    private static final String HTML_OUTPUT_DIR = "res/html/";
    
    private static String readAssumption(int index) throws IOException {
        String assumpationPath = SOLUTION_DIR + "q" + index + ".txt";
        if (!new File(assumpationPath).isFile()) {
            return "No assumptions were made.";
        }
        String result =  Utils.readFileAsString(assumpationPath);
        if (result.trim().equals("")) {
            return "No assumptions were made.";
        }
        return result;
    }
    
    private static String readSQLQuery(int index) throws IOException {
        String queryPath = SOLUTION_DIR + "q" + index + ".sql";
        if (!new File(queryPath).isFile()) {
            return "";
        }
        return Utils.readFileAsString(queryPath);
    }
    
    private static void writeQuestionToFile(Question question) throws IOException {
        Utils.writeStringToFile(question.toString(), HTML_OUTPUT_DIR + "q" + 
                question.getQuestionNumber()+ ".html");
    }
    
    private static void writeQuestionsToFile(Questions questions) throws IOException {
        Utils.writeStringToFile(questions.toString(), HTML_OUTPUT_DIR + "questions.html");
    }
    
    public static void main(String[] args) throws Exception {
        
        Connection con = null;
        Statement stmt;
        
        try {
            
            Class.forName(JDBC_DRIVER);
            con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
            stmt = con.createStatement();

            Questions questions = new Questions();
            
            for (int i=1; i<=NUMBER_OF_QUESTIONS; i++) {
                String assumption = readAssumption(i);
                String query = readSQLQuery(i);
                Question q = new Question(i, assumption, query);
                q.excecute(stmt);
                writeQuestionToFile(q);
                questions.add(q);
            }
        
            questions.excecute(stmt);
            writeQuestionsToFile(questions);
            
        } finally {
            if (con != null) {
                con.close();
            }
        }
        
    }
    
}
